<template>
  <div class="book">
    <div class="head-search">
      <search @onSubmit="onSearch">
        <el-form-item>
          <el-input placeholder="请输入内容" clearable v-model="searchData.val" size="small" class="input-with-select">
            <el-select v-model="searchData.select" clearable slot="prepend" placeholder="请选择">
              <el-option v-for="(item, index) in searchOptions"
                         :key="index"
                         :label="item.mdName"
                         :value="item.mdCode"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
      </search>
      <el-button @click="handleDrawer('search')" class="btn" type="primary" size="small">高级检索</el-button>
    </div>

    <section class="fun-btn">
      <el-button @click="handleInOut('3')"
                 type="primary"
                 icon="el-icon-circle-plus-outline"
                 v-if="btnJurisdiction['add']"
                 size="small">新增
      </el-button>

      <el-button @click="handleInOut('0')"
                 style="margin-left: 10px"
                 type="primary"
                 icon="el-icon-upload"
                 v-if="btnJurisdiction['imp']"
                 size="small">导入
      </el-button>
      <el-button @click="handleInOut('1')"
                 type="primary"
                 icon="el-icon-download"
                 v-if="btnJurisdiction['exp']"
                 size="small">导出
      </el-button>
      <el-button @click="handleInOut('2')"
                 style="margin-left: 10px"
                 icon="el-icon-s-data"
                 type="primary" size="small">报表
      </el-button>
      <el-button type="primary"
                 @click="handleFile"
                 v-if="btnJurisdiction['filing']"
                 size="small">归档</el-button>

      <el-button @click="handleDrawer('batchEdit')"
                 type="primary"
                 v-if="btnJurisdiction['mod'] || btnJurisdiction['rep']"
                 size="small">修改/替换
      </el-button>
      <!--<el-button class="btn" type="primary" size="small">挂接原文</el-button>-->
      <el-button @click="handleDrawer('set')"
                 type="primary"
                 icon="el-icon-setting"
                 size="small">设置</el-button>
      <el-button @click="handleDel"
                 type="danger"
                 plain
                 v-if="btnJurisdiction['delete']"
                 size="small">删除</el-button>
    </section>

    <section class="list-box">
      <el-table
        :data="tableData"
        border
        v-loading="tableLoading"
        height="calc(100vh - 252px)"
        @row-dblclick="handlerRowDblClick"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        class="table">
        <el-table-column
          align="center"
          type="selection"
          fixed="left"
          width="60">
        </el-table-column>
        <el-table-column
          align="center"
          type="index"
          label="序号"
          width="60">
        </el-table-column>

        <el-table-column
          v-for="(item, index) in headTableList"
          :key="index"
          :sortable="item.sort"
          show-overflow-tooltip
          :prop="item.mdCode"
          :label="item.mdName"
          :min-width="item.width"
          :align="item.mdCode === 'tm' ? 'left' : 'center'"
        >
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="130">
          <template slot-scope="scope">
              <el-button @click="handleInOut('5', scope.row)"
                         icon="el-icon-edit"
                         type="text">编辑</el-button>
              <el-button type="text" @click="handleInVolume(scope.row)">卷内</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="listTable"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTable ? Number(listTable.total) : 0">
      </el-pagination>
    </section>

    <el-drawer
      :title="setDrawer.title"
      :size="setDrawer.size"
      :direction="setDrawer.direction"
      :visible.sync="drawer"
      :destroy-on-close="true"
    ><!--:with-header="false"-->
      <arrange :fmtJson="fmtJson"
               :idCategory="idCategory"
               v-if="setDrawer.type === 'arrange'"></arrange>
      <edit-replace :idTable="idTable"
                    :tableSelected="tableSelected"
                    @handleSuccess="getList"
                    :idCategory="idCategory"
                    v-if="setDrawer.type === 'batchEdit'"></edit-replace>
      <set-up :idTable="idTable" v-if="setDrawer.type === 'set'"></set-up>

      <senior-search :idTable="idTable"
                     :idCategory="idCategory"
                     :qzDataSelect="qzDataSelect"
                     @handleSenior="handleSenior"
                     v-if="setDrawer.type === 'search'"></senior-search>
    </el-drawer>

    <!--:destroy-on-close="true"-->
    <el-dialog :title="dialogTitle"
               :width="dialogWidth"
               top="5vh"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :visible.sync="dialogVisible">
      <div class="import-content">
        <template-import v-if="dialogTitle === '导入'"></template-import>
        <template-export v-if="dialogTitle === '导出'"></template-export>

        <report-form :reportScope="reportScope"
                     @handlePreviewPrint="handlePreviewPrint"
                     :isSelect="tableSelected.length>0"
                     :isSearch="params.length>0"
                     :loading="previewPrintLoading"
                     v-if="dialogTitle === '报表'"></report-form>

        <add-volume :formOptions="formOptions"
                    :idTable="idTable"
                    :type="type"
                    :fmtJson="fmtJson"
                    :rowData="rowData"
                    :idCategory="idCategory"
                    @handleSuccess="handleAddEditSuccess"
                    v-if="dialogTitle === '新增案卷' || dialogTitle === '编辑'"></add-volume>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Search from '../../../../../components/search/search'
import TemplateImport from '../component/inOut/templateImport'
import TemplateExport from '../component/inOut/templateExport'
import Arrange from '../component/drawer/arrange'
import EditReplace from '../component/drawer/editReplace'
import SetUp from '../component/drawer/setUp'
import SeniorSearch from '../component/drawer/seniorSearch'
import AddVolume from './components/addVolume'
import { mapFields } from 'vuex-map-fields'
import { mapActions } from 'vuex'
import {
  delArchivesList,
  requestFile,
  requestPrint,
  requestRange
} from '../../../../../api/electronicsFile/electronicsFile'
import { getQzDic } from '../../../../../api/quanzong/quanzong'
import { getCategoryDicTypeName } from '../../../../../api/category/category'
import { getObjectURL } from '../../../../../util/util'
import ReportForm from '../../../../../components/reportForm/reportForm'

export default {
  name: 'BookFile', // 文书案卷
  props: {
    idTable: {
      type: String
    },
    idCategory: {
      type: String
    }
  },
  components: {
    ReportForm,
    AddVolume,
    SeniorSearch,
    SetUp,
    EditReplace,
    Arrange,
    TemplateExport,
    TemplateImport,
    Search
  },
  data () {
    return {
      drawer: false, // 新增
      dialogVisible: false, // 导入
      dialogTitle: '',
      dialogWidth: '80%',
      type: 'add',
      setDrawer: {
        title: '',
        size: '',
        direction: 'ltr'
      },
      searchData: {
        val: '', // 筛选
        select: '' // 筛选
      },
      page: {
        pageNo: 1,
        pageSize: 20
      },
      params: [],
      tableSelected: [],
      rowData: {}, // 某一条目的数据
      reportScope: [], // 报表范围
      previewPrintLoading: false, // 报表loading
      qzDataSelect: [], // 全宗号列表
      dictTypeName: {},
      sortSet: {}, // 记录排序点击后状态
      sortCondition: [] // 排序条件传入
    }
  },
  mounted () {
    this.getSearch()
    this.getDicTypeNames()
    getQzDic({
      pageNo: 1,
      pageSize: 1000
    }).then(res => {
      this.qzDataSelect = res.data.data.list
    })
  },
  computed: {
    ...mapFields('electronicsFile/getHead', {
      sortRetrieved: 'sortRetrieved',
      headTable: 'retrieved',
      listTable: 'listRetrieved',
      tableLoading: 'loading'
    }),
    ...mapFields('electronicsFile/getSearch', {
      searchOptions: 'retrieved'
    }),
    ...mapFields('electronicsFile/setSearchCondition', {
      searchParams: 'retrieved'
    }),
    ...mapFields('profile/getCategoryType', {
      categoryTreeType: 'dzFile'
    }),
    ...mapFields('profile/profile', {
      userInfo: 'retrieved'
    }),
    ...mapFields('profile/getDh', {
      dhgz: 'retrieved'
    }),
    fmtJson () {
      // 获取档号格式
      let fmtJson = []
      if (this.dhgz) {
        fmtJson = JSON.parse(this.dhgz.fmtJson)
      }
      return fmtJson
    },
    btnJurisdiction () {
      const btnShow = {}
      if (this.userInfo) {
        this.userInfo.perms.map(item => {
          if (item.indexOf('dzwj') > -1) {
            btnShow[item.split(':')[2]] = true
          }
        })
      }
      return btnShow
    },
    formType () {
      let type = ''
      if (this.idCategory) {
        this.categoryTreeType.category.map(item => {
          if (item.id === this.idCategory) {
            type = item.component
          }
        })
      }
      return type
    },
    headTableList () {
      return this.headTable ? this.headTable : []
    },
    tableData () {
      return this.listTable ? this.listTable.records : []
    },
    formOptions () {
      let options = {
        mockBtn: false,
        emptyBtn: false,
        submitBtn: false,
        labelWidth: 110,
        column: [
          {
            label: '全宗号',
            prop: 'qzh',
            span: 12,
            type: 'select',
            dicData: this.qzDataSelect,
            props: {
              label: 'fondsName',
              value: 'fondsNo'
            },
            slot: true
          },
          {
            label: '部门',
            prop: 'zldw',
            type: 'select',
            span: 12,
            props: {
              label: 'orgName',
              value: 'id'
            },
            rules: [{
              required: true,
              message: '请选择部门',
              trigger: 'blur'
            }]
          },
          {
            label: '归档年度',
            prop: 'gdnd',
            span: 12
          },
          {
            label: '目录号',
            prop: 'mlh',
            span: 12
          },
          {
            label: '案卷号',
            prop: 'ajh',
            span: 12
          },
          {
            label: '实体分类号',
            prop: 'flh',
            span: 12
          },
          {
            label: '保管期限',
            prop: 'bgqx',
            span: 12,
            type: 'select',
            dicUrl: `/yuyi-config-boot/api/config/arcDictType/child?dictTypeName=${this.dictTypeName.bgqx}`,
            props: {
              label: 'dictLabel',
              value: 'dictValue'
            }
          },
          {
            label: '案卷档号',
            prop: 'ajdh',
            type: 'input',
            span: 12
          },
          {
            label: '题名',
            prop: 'tm',
            type: 'textarea',
            maxRows: 6,
            minRows: 4,
            maxlength: 500,
            showWordLimit: true,
            span: 24,
            rules: [{
              required: true,
              message: '请输入题名',
              trigger: 'blur'
            }]
          },
          {
            label: '文件开始时间',
            prop: 'kssj',
            span: 12
          },
          {
            label: '结束时间',
            prop: 'jssj',
            span: 12
          },
          {
            label: '总页数',
            prop: 'ys',
            type: 'number',
            span: 12,
            minRows: 1,
            maxRows: 3000,
            row: true
          },
          {
            label: '归档日期',
            prop: 'gdrq',
            span: 12
          },
          {
            label: '总件数',
            prop: 'js',
            type: 'number',
            span: 12,
            minRows: 1,
            maxRows: 3000,
            row: true
          },
          {
            label: '密级',
            prop: 'mj',
            span: 12,
            type: 'select',
            dicUrl: `/yuyi-config-boot/api/config/arcDictType/child?dictTypeName=${this.dictTypeName.mj}`,
            props: {
              label: 'dictLabel',
              value: 'dictValue'
            }
          },
          {
            label: '备注',
            prop: 'bz',
            type: 'textarea',
            span: 24,
            maxRows: 6,
            minRows: 4,
            maxlength: 500,
            showWordLimit: true
          }
        ]
      }
      if (this.formType && this.categoryTreeType[this.formType]) {
        options = JSON.parse(JSON.stringify(this.categoryTreeType[this.formType].aj))
      }

      options.column.map(item => {
        if (item.prop === 'qzh') {
          item.dicData = this.qzDataSelect
        }
        if (item.prop === 'bgqx') {
          item.dicUrl = `/yuyi-config-boot/api/config/arcDictType/child?dictTypeName=${this.dictTypeName.bgqx}`
        }
        if (item.prop === 'mj') {
          item.dicUrl = `/yuyi-config-boot/api/config/arcDictType/child?dictTypeName=${this.dictTypeName.mj}`
        }
        if (item.prop === 'gdbs') {
          item.dicUrl = `/yuyi-config-boot/api/config/arcDictType/child?dictTypeName=${this.dictTypeName.gdbs}`
        }
      })

      return options
    }
  },
  methods: {
    ...mapActions('electronicsFile/getHead', ['getTableList']),
    ...mapActions('electronicsFile/getSearch', ['getSearchOptions']),
    async getSearch () {
      await this.getSearchOptions(this.idTable)
      this.searchData.select = this.searchOptions[0].mdCode
      this.searchOptions.map(item => {
        if (item.mdCode === 'tm') {
          this.searchData.select = 'tm'
        }
      })
    },
    getDicTypeNames () {
      // 获取数据字典需要传入的参数
      getCategoryDicTypeName(this.idTable, 'bgqx').then(res => {
        this.$set(this.dictTypeName, 'bgqx', res.data.data.dictTypeName)
      })
      getCategoryDicTypeName(this.idTable, 'mj').then(res => {
        this.$set(this.dictTypeName, 'mj', res.data.data.dictTypeName)
      })
      getCategoryDicTypeName(this.idTable, 'gdbs').then(res => {
        this.$set(this.dictTypeName, 'gdbs', res.data.data.dictTypeName)
      })
    },
    getList () {
      // 获取
      const param = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        params: this.searchParams.concat(this.params)
      }
      this.getTableList({
        idTable: this.idTable,
        data: param
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.page.pageNo = val
      this.getList()
    },
    handleSortChange (val) {
      this.$set(this.sortSet, val.prop, val.order)
      this.sortCondition = []
      Object.keys(this.sortSet).forEach(key => {
        if (this.sortSet[key]) {
          this.sortCondition.push({
            asc: this.sortSet[key] === 'ascending',
            name: key
          })
        }
      })
      this.page.pageNo = 1
      this.page.pageSize = 20
      this.getList()
    },
    onSearch () {
      // 搜索
      this.params = []
      if (this.searchData.val && this.searchData.select) {
        if (this.searchData.val.indexOf(' ') > -1) {
          const arr = this.searchData.val.split(' ')
          arr.map(item => {
            if (item) {
              this.params.push({
                name: this.searchData.select,
                op: 'like',
                value: item
              })
            }
          })
        } else {
          this.params.push({
            name: this.searchData.select,
            op: 'like',
            value: this.searchData.val
          })
        }
      }
      this.page.pageNo = 1
      this.page.pageSize = 20
      this.getList()
    },
    handleSenior () {
      this.page.pageNo = 1
      this.page.pageSize = 20
      this.drawer = false
    },
    handleSelectionChange (selection) {
      // 勾选表格行
      this.tableSelected = selection
    },
    handleFile () {
      // 归档
      if (this.tableSelected.length < 1) {
        this.$message.warning('请至少勾选一条数据进行归档操作！')
        return
      }
      const ids = []
      this.tableSelected.map(item => {
        ids.push(item.id)
      })
      this.$confirm('是否对当前选择的档案进行归档？归档的数据会进入电子档案管理模块。', '文件归档', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        requestFile(this.idTable, ids).then(() => {
          this.$confirm('你选择的文件归档成功，请到【电子档案管理】模块进行档案查询', '归档成功', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(() => {}).catch(() => {})
        }).catch(() => {
          this.$confirm('你选择的文件中存在未整理的档案，无法进行归档，请检查电子文件', '归档失败', {
            confirmButtonText: '确定',
            cancelButtonText: '取消' // 下载未整理信息
          }).then(() => {}).catch(() => {
            console.log('下载未整理信息')
          })
        })
      }).catch(() => {})
    },
    handleDel (row) {
      // 删除
      if (this.tableSelected.length > 0) {
        this.$confirm('此操作将永久删除该选中信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const ids = []
          this.tableSelected.map(item => {
            ids.push(item.id)
          })
          delArchivesList(this.idTable, ids).then(() => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        }).catch(() => {
        })
      } else {
        this.$message.warning('请最少选择一条数据进行删除操作！')
      }
    },
    handlerRowDblClick (row) {
      // 双击编辑
      this.handleInOut('5', row)
    },
    handleDrawer (type, row) {
      const arr = [{
        title: '整理',
        size: '100%',
        direction: 'ltr',
        type: 'arrange'
      }, {
        title: '修改/替换',
        size: '500px',
        direction: 'rtl', // 右边拉出
        type: 'batchEdit'
      }, {
        title: '设置',
        size: '80%',
        direction: 'rtl', // 右边拉出
        type: 'set'
      }, {
        title: '高级检索',
        size: '50%',
        direction: 'rtl', // 右边拉出
        type: 'search'
      }]
      if (type === 'edit') {
        this.rowData = row
      }
      if (type === 'batchEdit' && this.tableSelected.length < 1) {
        this.$message.warning('请最少选择一条信息进行修改/替换操作！')
        return
      }
      this.drawer = true
      this.type = type
      arr.map(item => {
        if (item.type === type) {
          this.setDrawer = item
        }
      })
    },
    handleInOut (type, row) {
      // 导入、导出、报表
      const arr = ['导入', '导出', '报表', '新增案卷', '新增卷内', '编辑']
      const minWidth = ['报表', '新增案卷', '新增卷内', '编辑']
      this.dialogVisible = true
      this.dialogTitle = arr[type]
      this.type = arr[type] === '新增案卷' ? 'add' : ''
      if (this.type === 'add') {
        this.rowData = this.tableSelected.length === 1 ? this.tableSelected[0] : {}
      }
      if (arr[type] === '编辑') {
        this.rowData = row
        this.type = 'edit'
      }
      this.dialogWidth = minWidth.includes(arr[type]) ? '70%' : '80%'
      if (arr[type] === '报表') {
        requestRange(this.idTable).then(res => {
          this.reportScope = res.data.data
        })
      }
    },
    handlePreviewPrint (val) {
      // 预览并打印报表
      this.previewPrintLoading = true
      const param = {
        idTable: this.idTable,
        idCategory: this.idCategory,
        filters: val.dataScope === 'search' ? this.params : [] // this.searchParams.concat(this.params)
      }
      if (val.dataScope === 'select') {
        param.ids = []
        this.tableSelected.map(item => {
          param.ids.push(item.id)
        })
      } else {
        delete param.ids
      }
      requestPrint({ ...val, ...param }).then((res) => {
        // 请求pdf流文件后转vue-pdf预览用的src
        window.open(getObjectURL(res.data), '_blank')
        this.$message.success('生成成功！')
        this.previewPrintLoading = false
        this.dialogVisible = false
      }).catch(() => {
        this.previewPrintLoading = false
      })
    },
    handleAddEditSuccess () {
      this.getList()
      this.dialogVisible = false
    },
    handleCommand (val) {
      if (val === '3') { this.handleInOut(val) }
      if (val === '4') {
        this.handleDrawer('add')
      }
    },
    handleInVolume (row) {
      // 卷内
      this.$emit('handleToIn', row)
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "../../../../../styles/mixin";

  .book {
    padding-top: 15px;

    .upload-demo {
      text-align: center;
    }

    .import-content {
      max-height: calc(90vh - 30px);
      overflow-y: auto;
    }

    ::v-deep .el-dialog{
      margin: 3vh auto 0 !important;
    }
    ::v-deep .el-dialog__body {
      padding: 10px 20px;
    }

  }

</style>
